# -*- coding: utf-8 -*-
# @File: backend => redis.py
# @CreateTime: 2025/8/25 14:43
# @Author: EvanZhang
# @Info: Redis 连接池配置
import redis.asyncio as redis
from contextlib import asynccontextmanager
from typing import AsyncGenerator

# Redis 配置
REDIS_HOST = "localhost"
REDIS_PORT = 6379
REDIS_DB = 15
REDIS_POOL_MIN_SIZE = 10  # 最小连接数
REDIS_POOL_MAX_SIZE = 50  # 最大连接数

# Redis 连接池依赖函数
async def init_redis_pool() -> AsyncGenerator[redis.Redis, None]:
    """
    创建并返回 Redis 连接池。通过依赖注入管理 Redis 连接池。
    """
    pool = redis.ConnectionPool.from_url(
        f'redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_DB}',
        encoding="utf-8",
        max_connections=REDIS_POOL_MAX_SIZE   # 设置最大连接数
    )
    redis_client = redis.Redis(connection_pool=pool)
    try:
        yield redis_client
    finally:
        await redis_client.aclose()

# 新增的上下文管理器，用于非依赖注入场景
@asynccontextmanager
async def init_redis_pool_without_depend():
    """
    获取Redis连接的上下文管理器，用于直接调用场景
    """
    pool = redis.ConnectionPool.from_url(
        f'redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_DB}',
        encoding="utf-8",
        max_connections=REDIS_POOL_MAX_SIZE
    )
    redis_client = redis.Redis(connection_pool=pool)
    try:
        yield redis_client
    finally:
        await redis_client.aclose()